package com.ukao.cashregister.ui.stokin;


import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.KeyboardAdapter;
import com.ukao.cashregister.base.BaseFragment;
import com.ukao.cashregister.bean.BalanceBean;
import com.ukao.cashregister.bean.PayInfoBean;
import com.ukao.cashregister.consts.Constant;
import com.ukao.cashregister.consts.SaveParamets;
import com.ukao.cashregister.eventbus.PayAmountEvent;
import com.ukao.cashregister.eventbus.PayEvent;
import com.ukao.cashregister.listener.OnItemClickListener;
import com.ukao.cashregister.retrofit.ApiCallback;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.DecimalUtil;
import com.ukao.cashregister.utils.L;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.utils.Utils;
import com.ukao.cashregister.widget.StateButton;
import com.ukao.cashregister.widget.StateImageView;

import org.greenrobot.eventbus.Subscribe;

import java.util.Arrays;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Observable;


/**
 * 现金
 */
public class CashFragment extends BaseFragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    Unbinder unbinder;
    @BindView(R.id.gather_num)
    TextView gatherNum;
    @BindView(R.id.remove)
    StateImageView remove;
    @BindView(R.id.all_remove)
    StateButton allRemove;
    @BindView(R.id.sure_gather)
    StateButton sureGather;
    @BindView(R.id.odd_change_txt)
    TextView oddChangeTxt;


    private String orderId;
    private String shouldPice;
    private KeyboardAdapter mKeyboardAdapter;
    private int balance;
    private PayInfoBean mPayInfo;
    private String userId;

    private String rechargeAmount;
    private String withActive="";

    public static CashFragment newInstance(String param1, String param2, String rechargeAmount,String  withActive) {
        CashFragment fragment = new CashFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        args.putString(ARG_PARAM3, rechargeAmount);
        args.putString(ARG_PARAM4, withActive);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        String    orderId = getArguments().getString(ARG_PARAM1,"");
                userId= getArguments().getString(ARG_PARAM2,"");
            rechargeAmount= getArguments().getString(ARG_PARAM3,"");
            withActive= getArguments().getString(ARG_PARAM4);
            if (!CheckUtils.isEmpty(rechargeAmount)){
                shouldPice=rechargeAmount;
            }
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_cash, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initListener();
        return view;
    }


    @Override
    protected boolean useEventBus() {
        return true;
    }

     @Subscribe
    public void onEvent(PayAmountEvent event) {
        switch (event.getMessage()) {
            case PAY_COUNT:
                mPayInfo = (PayInfoBean) event.getData();
                balance = mPayInfo.getPayBalance();
                shouldPice = mPayInfo.getShouldPrice()+"";
                orderId=mPayInfo.getOrderId();
                showOddChange(getText(gatherNum));
                break;
            case  recharge: /*充值信息*/
                HashMap   mHashMap=(HashMap)event.getData();
                rechargeAmount= (String) mHashMap.get(ARG_PARAM1);
                withActive= (String) mHashMap.get(ARG_PARAM2);
                shouldPice=rechargeAmount;
                showOddChange(getText(gatherNum));
                break;
        }
    }

    @Override
    protected void initView() {
        String[] keyBoardData = getResources().getStringArray(R.array.gather_keyboard);
        initGridRecyclerView(recyclerView, 3);
        mKeyboardAdapter = new KeyboardAdapter(activity, Arrays.asList(keyBoardData));
        recyclerView.setAdapter(mKeyboardAdapter);

    }

    @Override
    protected void initListener() {
        super.initListener();
        mKeyboardAdapter.setOnClickListener(mOnItemClickListener);


    }

    OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

        @Override
        public void onSureItemClick(Object item, int pos) {
            String message = (String) item;
            String s = gatherNum.getText().toString().trim();
            s = s + message;
            showOddChange(s);


        }


    };


    /**
     * 找零
     *
     * @param s
     */
    public void showOddChange(String s) {
        gatherNum.setText(s);
        if (!CheckUtils.isEmpty(s)) {
            if (s.contains(".")) {
                if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                    s = (String) s.subSequence(0,
                            s.indexOf(".") + 3);
                    gatherNum.setText(s);

                }
            }
            if (s.trim().substring(0).equals(".")) {
                s = "0" + s;
                gatherNum.setText(s);

            }
            if (s.startsWith("0")
                    && s.toString().trim().length() > 1) {
                if (!s.toString().substring(1, 2).equals(".")) {
                    gatherNum.setText(s.subSequence(0, 1));


                }
            }

            try {


                String  pice=DecimalUtil.subtract(s,!CheckUtils.isEmpty(userId)? shouldPice : DecimalUtil.divide(shouldPice,"100"));
                Double flopice =Double.valueOf(pice) ;

                if (flopice < 0) {
                    oddChangeTxt.setText("");

                } else {
                    Spannable span = new SpannableString(pice);
                    if (pice.indexOf(".") != -1)
                        span.setSpan(new AbsoluteSizeSpan(60), pice.indexOf("."), pice.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                      oddChangeTxt.setText(span);
                }


            } catch (Exception e) {

            }
        } else {
            oddChangeTxt.setText("");

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.remove, R.id.all_remove, R.id.sure_gather})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.remove:
                String removeGatherNum = gatherNum.getText().toString().trim();
                if (!CheckUtils.isEmpty(removeGatherNum))

                    showOddChange(removeGatherNum.substring(0, removeGatherNum.length() - 1));
                break;
            case R.id.all_remove:
                String strgatherNum = gatherNum.getText().toString().trim();
                if (!CheckUtils.isEmpty(strgatherNum))
                    showOddChange("");
                break;
            case R.id.sure_gather:
                String  strGatherNum=getText(gatherNum);
                String  stroddChangeTxt=getText(oddChangeTxt);

                if (CheckUtils.isEmpty(strGatherNum)){
                    T.show("请输入收款金额");
                    return;
                }else if (CheckUtils.isEmpty(stroddChangeTxt)){
                    T.show("收款金额不足");
                    return;
                }

                confirmPay();

                break;
        }
    }

    /**
     *  把收款金额传入服务器。
     *  确定收款
     */
    public void confirmPay() {
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("accessToken", SaveParamets.getToken(Utils.getContext()));
        Observable observable=null;
        if (!CheckUtils.isEmpty(userId)){
            mHashMap.put("withActive",withActive);
            mHashMap.put("userId",userId);
            mHashMap.put("amount",DecimalUtil.multiply(rechargeAmount));
            observable=apiStores().confirmRecharge(Constant.createParameter(mHashMap));
        }else if (!CheckUtils.isNull(mPayInfo)){

            mHashMap.put("orderId", orderId);
            if(mPayInfo.isUseUPay()){
                mHashMap.put("groupCardType","41");//groupCardType 支付(团)卡类型 41-优付卡
            }else{
                mHashMap.put("balance",String.valueOf(balance));
            }
            if (!CheckUtils.isEmpty(mPayInfo.getCpnRelId())){
                mHashMap.put("cpnRelId", mPayInfo.getCpnRelId());
            }
            observable=apiStores().confirmPay(Constant.createParameter(mHashMap));
        }
        if (observable==null){
            return;
        }
        L.i("mHashMap="+mHashMap.toString());
        showProgressDialog();
        addSubscription(observable,
                new ApiCallback<BalanceBean>() {
                    @Override
                    public void onSuccess(BalanceBean model) {
                        if (model.getHttpCode() == 200) {
                            PayEvent.postNoData(PayEvent.Message.PAY_SUCCEED);
                        } else {
                            T.show(model.getMsg());
                        }

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }

                });
    }

}
